package pay.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import org.springframework.stereotype.Service;
import pay.commont.UserVipStatus;
import pay.service.CouponAppUserService;
import pay.dao.SystemUserAppDao;
import pay.dao.VipHistoryMapper;
import pay.entity.SystemUserAppEntity;
import pay.entity.VipHistoryEntity;
import pay.service.MessageService;

import java.util.Date;

@Service
public class VipUtils {

    @Autowired
    VipHistoryMapper vipHistoryMapper;

    @Autowired
    SystemUserAppDao systemUserAppDao;

    private static final String SERVER_ERROR = "服务器内部错误";

    @Transactional
    public void activateMember(String userId, String operatorId, int days, int vipSource) {
        activateMember(userId, operatorId, days, vipSource, null);
    }

    @Transactional
    public void activateMember(String userId, String operatorId, int days, int vipSource, Integer orderId) {
        VipHistoryEntity vipHistory = createVipHistory(userId, operatorId, days, vipSource, orderId);

        VipHistoryMapper vipHistoryMapper = SpringContextUtils.getBean(VipHistoryMapper.class);
        SystemUserAppDao systemUserAppDao = SpringContextUtils.getBean(SystemUserAppDao.class);
        CouponAppUserService couponAppUserService = SpringContextUtils.getBean(CouponAppUserService.class);
        MessageService messageService = SpringContextUtils.getBean(MessageService.class);

        // 插入 VIP 历史记录
        insertVipHistory(vipHistoryMapper, vipHistory);

        // 处理用户 VIP 状态
        processUserVipStatus(systemUserAppDao, userId, days, couponAppUserService, messageService);
    }

    private VipHistoryEntity createVipHistory(String userId, String operatorId, int days, int vipSource, Integer orderId) {
        VipHistoryEntity vipHistory = new VipHistoryEntity();
        vipHistory.setUserId(userId);
        vipHistory.setDays(days);
        vipHistory.setVipSource(vipSource);
        vipHistory.setOrderId(orderId);
        vipHistory.setCreateTime(new Date());
        vipHistory.setOperatorId(operatorId);
        return vipHistory;
    }

    private void insertVipHistory(VipHistoryMapper vipHistoryMapper, VipHistoryEntity vipHistory) {
        int insertResult = vipHistoryMapper.insert(vipHistory);
        if (insertResult <= 0) {
            throw new RuntimeException(SERVER_ERROR);
        }
    }

    private void processUserVipStatus(SystemUserAppDao systemUserAppDao, String userId, int days,
                                      CouponAppUserService couponAppUserService, MessageService messageService) {
        SystemUserAppEntity user = systemUserAppDao.selectOne(new QueryWrapper<SystemUserAppEntity>().eq("user_id", userId));
        if (user != null) {
            updateUserVipInfo(user, days, userId, couponAppUserService, messageService);
            updateUserInDatabase(systemUserAppDao, user);
        }
    }

    private void updateUserVipInfo(SystemUserAppEntity user, int days, String userId,
                                   CouponAppUserService couponAppUserService, MessageService messageService) {
        if (user.getIsVip() != UserVipStatus.YES.getCode()) {
            // 新 VIP 用户
            initializeNewVipUser(user, days, userId, couponAppUserService, messageService);
        } else {
            // 续费 VIP 用户
            extendExistingVipUser(user, days);
        }
    }

    private void initializeNewVipUser(SystemUserAppEntity user, int days, String userId,
                                      CouponAppUserService couponAppUserService, MessageService messageService) {
        user.setVipStartTime(new Date());
        user.setVipEndTime(DateUtils.addDateDays(user.getVipStartTime(), days));
        user.setIsVip(UserVipStatus.YES.getCode());
        // 发放优惠券
        couponAppUserService.grantVipCoupon(userId);
        messageService.vipCouponSendMessage(userId);
    }

    private void extendExistingVipUser(SystemUserAppEntity user, int days) {
        user.setVipEndTime(DateUtils.addDateDays(user.getVipEndTime(), days));
    }

    private void updateUserInDatabase(SystemUserAppDao systemUserAppDao, SystemUserAppEntity user) {
        int updateResult = systemUserAppDao.updateById(user);
        if (updateResult <= 0) {
            throw new RuntimeException(SERVER_ERROR);
        }
    }
}